<?php

namespace app\thirdPay\logic;

use app\data\util\HttpUtil;
use think\facade\Db;
use think\facade\Config;
use think\facade\Cache;

class TiktokPayServiceLogic
{
    protected $model = null;

    public function __construct()
    {

    }
    /**
     * 获取回款
     * @param $type
     * @return mixed
     */
    public function GetPaymentsTiktokPay($params=[])
    {
        $where = [];
        if(isset($params['type']) && $params['type'] == 2){
            $where[] = ["payments_page_token","<>","拉取历史数据完成"];
        }
        $shops = Db::name('shops')
            // ->where('id',9)
            ->where($where)
            ->select()
            ->toarray();
        if(!empty($shops)){
            foreach ($shops as $k=>$shop) {
                $shop_id = $shop['id'];
                $this->GetPaymentsList($shop_id,$params);
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }
    /**
     * 获取回款
     * @param $type
     * @return mixed
     */
    public function GetPaymentsList($shop_id,$params)
    {
        $type   = $params['type']??1;
        $shop      = Db::name('shops')
            ->where("id", $shop_id)
            ->find();
        $url       = Config('Logisticskey.TIKTOK.basic_url');
        $path      = Config('Logisticskey.TIKTOK.pay_amount_path');

        switch ($type) {
            case '1'://更新当前
                // &sort_field=create_time&sort_order=ASC&create_time_ge=1714492800
                $create_time_ge = strtotime(date('Y-m-d', time() - 3600*16 - 3600*24));
                $sign      = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'create_time_ge'.$create_time_ge.'page_size100shop_cipher' . $shop['cipher'] . 'sort_fieldcreate_timesort_orderASCtimestamp' . time() . '' . $shop['app_secret'];
                $sign      = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url       = $url . "" . $path . "?app_key=" . $shop['app_key'] . "&create_time_ge=".$create_time_ge."&page_size=100&shop_cipher=" . $shop['cipher'] . "&sort_field=create_time&sort_order=ASC&sign=" . $sign . "&timestamp=" . time();

                break;
            case '2'://拉取历史 拉取2024-06-01之前的所有记录-按page_token分页
                // &create_time_lt=1717171200&sort_field=create_time&sort_order=DESC
                $create_time_lt = (int)1717641232;
                $sign      = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'create_time_lt'.$create_time_lt.'page_size100page_token' . $shop['payments_page_token'] . 'shop_cipher' . $shop['cipher'] . 'sort_fieldcreate_timesort_orderDESCtimestamp' . time() . '' . $shop['app_secret'];
                $sign      = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url       = $url . "" . $path . "?app_key=" . $shop['app_key'] . "&create_time_lt=".$create_time_lt."&page_size=100&page_token=" . $shop['payments_page_token'] . "&shop_cipher=" . $shop['cipher'] . "&sort_field=create_time&sort_order=DESC&sign=" . $sign . "&timestamp=" . time();

                break;
            default:
        }

        $return    = HttpUtil::tikGetUrl($url, $shop['access_token']);

        if($return['code']==0 && $return['data']['payments']){
            if(!empty($return['data']['next_page_token'])){
                Db::name('shops')
                    ->where('id',$shop_id)
                    ->update(
                        [
                            'payments_page_token'=>$return['data']['next_page_token']
                        ]
                    );
            }else{
                if($type == 2){
                    Db::name('shops')
                    ->where('id',$shop_id)
                    ->update(
                        [
                            'payments_page_token'=>"拉取历史数据完成"
                        ]
                    );
                }
            }

            //设置时间
            $payments = $return['data']['payments'];
            foreach ($payments as $k=>$v) {
                $payments_list = [
                    'shop_id'                        => $shop['id'],
                    'bank_account'                   => $v['bank_account']??'0',
                    'amount'                         => $v['amount']['value']??'0',
                    'currency'                       => $v['amount']['currency']??'0',
                    'settlement_amount'              => $v['settlement_amount']['value']??'0',
                    'reserve_amount'                 => $v['reserve_amount']['value']??'0',
                    'payment_amount_before_exchange' => $v['payment_amount_before_exchange']['value']??'0',
                    'exchange_rate'                  => $v['exchange_rate']??'0',
                    'pay_status'                     => $v['status']??'0',
                    'createtime'                     => $v['create_time']??0,
                    'paid_time'                      => $v['paid_time']??0,
                    'pay_id'                         => $v['id']??0,
                    'date'                           =>date('Y-m',$v['create_time']),
                ];
                $bank_pay_info = Db::name('bank_pay_info')->where('pay_id',$payments_list['pay_id'])->find();
                if(!empty($bank_pay_info)){
                    Db::name('bank_pay_info')->where('id',$bank_pay_info['id'])->update($payments_list);
                }else{
                    Db::name('bank_pay_info')->insert($payments_list);
                }
            }
        }
        return true;
    }


}

